import 'dart:async';
import 'dart:io';
import 'dart:ui';

import 'package:animated_text_kit/animated_text_kit.dart';
import 'package:chatgreat/helper/ability.dart';
import 'package:chatgreat/helper/color.dart';
import 'package:chatgreat/helper/haptic_feedback.dart';
import 'package:chatgreat/helper/helper.dart';
import 'package:chatgreat/helper/my_widget.dart';
import 'package:chatgreat/helper/platform.dart';
import 'package:chatgreat/lang/lang.dart';
import 'package:chatgreat/page/component/chat/file_upload.dart';
import 'package:chatgreat/page/component/chat/voice_record.dart';
import 'package:chatgreat/page/component/dialog.dart';
import 'package:chatgreat/page/component/theme/custom_size.dart';
import 'package:chatgreat/repo/settings_repo.dart';
import 'package:circular_countdown_timer/circular_countdown_timer.dart';
import 'package:file_picker/file_picker.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter/services.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_localization/flutter_localization.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_slidable/flutter_slidable.dart';
import 'package:chatgreat/page/component/theme/custom_theme.dart';
import 'package:flutter_speech/flutter_speech.dart';
import 'package:go_router/go_router.dart';
import 'package:loading_animation_widget/loading_animation_widget.dart';
import 'package:loading_more_list/loading_more_list.dart';
import 'package:media_kit_video/media_kit_video_controls/src/controls/methods/video_state.dart';
import 'package:notification_center/notification_center.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:url_launcher/url_launcher.dart';
import 'package:url_launcher/url_launcher_string.dart';

import '../../../helper/AppUtil.dart';
import '../../../helper/constant.dart';
import '../../../helper/event.dart';
import '../../creative_island/draw/draw_result.dart';

class ChatInput extends StatefulWidget {
  final int keyIndex;
  final Function(String value) onSubmit;
  final ValueNotifier<bool> enableNotifier;
  final Widget? toolbar;
  final bool enableImageUpload;
  final Function(List<FileUpload> files)? onImageSelected;
  final List<FileUpload>? selectedImageFiles;
  final Function()? onNewChat;
  final String hintText;
  final Function()? onVoiceRecordTappedEvent;
  final List<Widget> Function()? leftSideToolsBuilder;
  final Function()? onStopGenerate;
  final Function(bool hasFocus)? onFocusChange;
  final Function()? onAlertVipTappedEvent;

  const ChatInput({
    super.key,
    required this.keyIndex,
    required this.onSubmit,
    required this.enableNotifier,
    this.enableImageUpload = true,
    this.toolbar,
    this.onNewChat,
    this.hintText = '',
    this.onVoiceRecordTappedEvent,
    this.leftSideToolsBuilder,
    this.onImageSelected,
    this.selectedImageFiles,
    this.onStopGenerate,
    this.onFocusChange,
    this.onAlertVipTappedEvent,
  });

  @override
  ChatInputState createState() => ChatInputState();
}

class ChatInputState extends State<ChatInput> with TickerProviderStateMixin {
  final TextEditingController _textController = TextEditingController();
  late SpeechRecognition _speech;

  final maxLength = 150000;
  // Maximum height of the chat input box
  var maxLines = 5;

  // 监听内容
  var listenContent = '';
  bool _speechRecognitionAvailable = false;
  bool _isListening = false;

  CountDownController controller = CountDownController();

  StateSetter? dialogState;
  BuildContext? dialogContext;
  // 用于监听键盘事件，实现回车发送消息，Shift+Enter换行
  late final FocusNode _focusNode = FocusNode(
    onKeyEvent: (node, event) {
      if (!HardwareKeyboard.instance.isShiftPressed &&
          event.logicalKey.keyLabel == 'Enter') {
        if (event is KeyDownEvent && widget.enableNotifier.value) {
          _handleSubmited(_textController.text.trim());
        }

        return KeyEventResult.handled;
      } else {
        return KeyEventResult.ignored;
      }
    },
  );

  @override
  void dispose() {
    _textController.dispose();
    if (widget.keyIndex == 1) {
      NotificationCenter().unsubscribe(HOME_EDIT_INPUT_TEXT_ONE_NOTIF);
      GlobalEvent().off(HOME_CHAT_CLEAR_ONE_NOTIF);
    } else if (widget.keyIndex == 2) {
      NotificationCenter().unsubscribe(HOME_EDIT_INPUT_TEXT_TWO_NOTIF);
      GlobalEvent().off(HOME_CHAT_CLEAR_TWO_NOTIF);
    }
    super.dispose();
  }

  @override
  void initState() {
    super.initState();
    _speech = SpeechRecognition();
    _textController.addListener(() {
      setState(() {});
    });

    // AI回复完成后自动输入框自动获取焦点
    if (!PlatformTool.isAndroid() && !PlatformTool.isIOS()) {
      widget.enableNotifier.addListener(() {
        if (widget.enableNotifier.value) {
          _focusNode.requestFocus();
        }
      });
    }
    initNotif();
  }

  void initNotif() {
    if (widget.keyIndex == 1) {
      // 接收编辑事件
      NotificationCenter().subscribe(HOME_EDIT_INPUT_TEXT_ONE_NOTIF, (data) {
        if (data is String) {
          print('------------> $data');
          _textController.text = data.replaceAll('\\', '');
        }
      });

      GlobalEvent().on(HOME_CHAT_CLEAR_ONE_NOTIF, (data) {
        if (mounted) {
          _textController.clear();
          if (widget.onVoiceRecordTappedEvent != null) {
            widget.onVoiceRecordTappedEvent?.call();
          }
        }
      });
    } else if (widget.keyIndex == 2) {
      // 接收编辑事件
      NotificationCenter().subscribe(HOME_EDIT_INPUT_TEXT_TWO_NOTIF, (data) {
        if (data is String) {
          print('------------> $data');
          _textController.text = data.replaceAll('\\', '');
        }
      });

      GlobalEvent().on(HOME_CHAT_CLEAR_TWO_NOTIF, (data) {
        if (mounted) {
          _textController.clear();
          if (widget.onVoiceRecordTappedEvent != null) {
            widget.onVoiceRecordTappedEvent?.call();
          }
        }
      });
    }
  }

  /// 初始化识别器
  void setupSpeechRecognition() async {
    _speech.setAvailabilityHandler(onSpeechAvailability);
    _speech.setRecognitionStartedHandler(onRecognitionStarted);
    _speech.setRecognitionResultHandler(onRecognitionResult);
    _speech.setRecognitionCompleteHandler(onRecognitionComplete);
    _speech.setErrorHandler(errorHandler);
    _speechRecognitionAvailable = await _speech.activate('zh_CN');

    if (_speechRecognitionAvailable && !_isListening) {
      startRecognition();
    }
  }

  @override
  Widget build(BuildContext context) {
    final customColors = Theme.of(context).extension<CustomColors>()!;
    return SafeArea(
      child: Container(
        padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 12),
        decoration: BoxDecoration(
          color: const Color(0xFF020103).withOpacity(0.2),
        ),
        child: Builder(builder: (context) {
          final setting = context.read<SettingRepository>();
          return Column(
            children: [
              // if (widget.selectedImageFiles != null &&
              //     widget.selectedImageFiles!.isNotEmpty)
              //   SizedBox(
              //     height: 110,
              //     child: ListView(
              //       scrollDirection: Axis.horizontal,
              //       children: widget.selectedImageFiles!
              //           .map(
              //             (e) => Container(
              //               margin: const EdgeInsets.only(right: 8),
              //               padding: const EdgeInsets.all(5),
              //               child: Stack(
              //                 children: [
              //                   ClipRRect(
              //                     borderRadius: BorderRadius.circular(5),
              //                     child: e.file.bytes != null
              //                         ? Image.memory(
              //                             e.file.bytes!,
              //                             fit: BoxFit.cover,
              //                             width: 100,
              //                             height: 100,
              //                           )
              //                         : Image.file(
              //                             File(e.file.path!),
              //                             fit: BoxFit.cover,
              //                             width: 100,
              //                             height: 100,
              //                           ),
              //                   ),
              //                   if (widget.enableNotifier.value)
              //                     Positioned(
              //                       right: 5,
              //                       top: 5,
              //                       child: InkWell(
              //                         onTap: () {
              //                           setState(() {
              //                             widget.selectedImageFiles!.remove(e);
              //                             widget.onImageSelected
              //                                 ?.call(widget.selectedImageFiles!);
              //                           });
              //                         },
              //                         child: Container(
              //                           padding: const EdgeInsets.all(3),
              //                           decoration: BoxDecoration(
              //                             borderRadius: BorderRadius.circular(10),
              //                             color: customColors.chatRoomBackground,
              //                           ),
              //                           child: Icon(
              //                             Icons.close,
              //                             size: 10,
              //                             color: customColors.weakTextColor,
              //                           ),
              //                         ),
              //                       ),
              //                     ),
              //                 ],
              //               ),
              //             ),
              //           )
              //           .toList(),
              //     ),
              //   ),
              // 工具栏
              if (widget.toolbar != null) widget.toolbar!,
              // 聊天内容输入栏
              SingleChildScrollView(
                child: Slidable(
                  startActionPane: widget.onNewChat != null
                      ? ActionPane(
                          extentRatio: 0.3,
                          motion: const ScrollMotion(),
                          children: [
                            SlidableAction(
                              autoClose: true,
                              label: AppLocale.newChat.getString(context),
                              backgroundColor: Colors.blue,
                              borderRadius:
                                  const BorderRadius.all(Radius.circular(20)),
                              onPressed: (_) {
                                widget.onNewChat!();
                              },
                            ),
                            const SizedBox(width: 10),
                          ],
                        )
                      : null,
                  child: Row(
                    children: [
                      // 聊天功能按钮
                      Row(
                        children: [
                          if (widget.leftSideToolsBuilder != null)
                            ...widget.leftSideToolsBuilder!(),
                          if (widget.enableNotifier.value &&
                              widget.enableImageUpload &&
                              Ability().supportImageUploader &&
                              widget.onImageSelected != null &&
                              Ability().supportWebSocket)
                            _buildImageUploadButton(
                                context, setting, customColors),
                        ],
                      ),
                      // 聊天输入框
                      Expanded(
                        child: Container(
                          decoration: BoxDecoration(
                            color: Colors.transparent,
                            borderRadius: BorderRadius.circular(13),
                            border: Border.all(
                              color: const Color(0xFFE1E1E1), // 边框颜色
                              width: 0.5, // 边框宽度
                            ),
                          ),
                          padding: const EdgeInsets.only(left: 14),
                          child: Row(
                            crossAxisAlignment: CrossAxisAlignment.center,
                            children: [
                              Expanded(
                                child: Focus(
                                  onFocusChange: (hasFocus) {
                                    setState(() {
                                      // if (hasFocus) {
                                      //   maxLines = 10;
                                      // } else {
                                      //   maxLines = 5;
                                      // }
                                      maxLines = 5;
                                    });

                                    widget.onFocusChange?.call(hasFocus);
                                  },
                                  child: TextFormField(
                                    textAlignVertical: TextAlignVertical.center,
                                    keyboardType: TextInputType.multiline,
                                    textInputAction: TextInputAction.newline,
                                    maxLines: maxLines,
                                    minLines: 1,
                                    maxLength: maxLength,
                                    focusNode: _focusNode,
                                    controller: _textController,
                                    onChanged: (string) {},
                                    style: const TextStyle(
                                      textBaseline: TextBaseline.alphabetic,
                                      fontSize: 15,
                                      fontWeight: FontWeight.w500,
                                    ),
                                    decoration: InputDecoration(
                                      // contentPadding: const EdgeInsets.only(bottom: 15),
                                      hintText: widget.hintText,
                                      hintStyle: const TextStyle(
                                          fontSize: 15,
                                          fontWeight: FontWeight.w500,
                                          textBaseline:
                                              TextBaseline.alphabetic),
                                      border: InputBorder.none,
                                      counterText: '',
                                    ),
                                  ),
                                ),
                              ),
                              // 语音按钮
                              _buildrVoiceButton(context, customColors),
                            ],
                          ),
                        ),
                      ),
                      const SizedBox(
                        width: 9.5,
                      ),
                      if (widget.enableNotifier.value)
                        InkWell(
                          onTap: () {
                            _handleSubmited(_textController.text.trim());
                          },
                          child: Padding(
                            padding: const EdgeInsets.only(right: 0),
                            child: Image.asset('images/send.png'),
                          ),
                        )
                    ],
                  ),
                ),
              ),
            ],
          );
        }),
      ),
    );
  }

  /// 构建语音按钮
  Widget _buildrVoiceButton(
    BuildContext context,
    CustomColors customColors,
  ) {
    if (!widget.enableNotifier.value) {
      return InkWell(
        onTap: () {
          // if (widget.onStopGenerate != null) {
          //   openConfirmDialog(
          //     context,
          //     '确定要停止当前输出？',
          //     () {
          //       widget.onStopGenerate!();
          //       HapticFeedbackHelper.heavyImpact();
          //     },
          //     danger: true,
          //   );
          // }
        },
        child: Container(
          padding: const EdgeInsets.only(right: 15),
          child: LoadingAnimationWidget.beat(
            color: customColors.themeBlueColor ?? Colors.transparent,
            size: 20,
          ),
        ),
      );
    }

    return InkWell(
      onTap: () => showRecordInputDialog(),
      child: Container(
        padding:
            const EdgeInsets.only(top: 10, bottom: 10, left: 16, right: 15),
        child: Image.asset('images/microphone.png'),
      ),
    );
  }

  /// 构建图片上传按钮
  Widget _buildImageUploadButton(
    BuildContext context,
    SettingRepository setting,
    CustomColors customColors,
  ) {
    return IconButton(
      onPressed: () async {
        HapticFeedbackHelper.mediumImpact();
        if (widget.selectedImageFiles != null &&
            widget.selectedImageFiles!.length >= 4) {
          showSuccessMessage('最多只能上传 4 张图片');
          return;
        }

        FilePickerResult? result = await FilePicker.platform.pickFiles(
          type: FileType.image,
          allowMultiple: true,
        );
        if (result != null && result.files.isNotEmpty) {
          final files = widget.selectedImageFiles ?? [];
          files.addAll(result.files.map((e) => FileUpload(file: e)).toList());
          widget.onImageSelected
              ?.call(files.sublist(0, files.length > 4 ? 4 : files.length));
        }
      },
      icon: const Icon(Icons.camera_alt),
      color: customColors.chatInputPanelText,
      splashRadius: 20,
      tooltip: AppLocale.uploadImage.getString(context),
    );
  }

  Future<bool> requestMicrophonePermission() async {
    final status = await Permission.microphone.request();
    return status == PermissionStatus.granted;
  }

  Future<bool> requestSpeechPermission() async {
    final status = await Permission.speech.request();
    return status == PermissionStatus.granted;
  }

  void showRecordInputDialog() async {
    widget.onVoiceRecordTappedEvent?.call();
    // 麦克风权限
    final microphoneStatus = await Permission.microphone.status;
    if (microphoneStatus != PermissionStatus.granted) {
      // 用户尚未授权，可以尝试请求权限
      bool granted = await requestMicrophonePermission();
      if (!granted) {
        // 用户拒绝了权限请求，可以引导用户到设置页面
        showCupertinoDialog(
            context: context,
            builder: (BuildContext context) {
              return CupertinoAlertDialog(
                title: const Text('提示'),
                content: const Text('你未授权访问麦克风，无法使用语音交流功能，请在设置中允许访问麦克风权限后重试'),
                actions: [
                  CupertinoDialogAction(
                    isDefaultAction: true,
                    child: const Text(
                      '取消',
                      style: TextStyle(
                          color: Colors.white, fontWeight: FontWeight.normal),
                    ),
                    onPressed: () {
                      Navigator.of(context).pop();
                    },
                  ),
                  CupertinoDialogAction(
                    isDestructiveAction: true,
                    child: const Text('去设置'),
                    onPressed: () {
                      launchUrlString('App-Prefs:Privacy&path=MICROPHONE');
                    },
                  ),
                ],
                insetAnimationDuration: Duration(seconds: 2),
              );
            });
        return;
      }
    }
    // 语音识别权限
    final speechStatus = await Permission.speech.status;
    if (speechStatus != PermissionStatus.granted) {
      // 用户尚未授权，可以尝试请求权限
      bool granted = await requestSpeechPermission();
      if (!granted) {
        // 用户拒绝了权限请求，可以引导用户到设置页面
        showCupertinoDialog(
            context: context,
            builder: (BuildContext context) {
              return CupertinoAlertDialog(
                title: const Text('提示'),
                content: const Text('你未授权访问语音识别，无法使用语音交流功能，请在设置中允许访问语音识别权限后重试'),
                actions: [
                  CupertinoDialogAction(
                    isDefaultAction: true,
                    child: const Text(
                      '取消',
                      style: TextStyle(
                          color: Colors.white, fontWeight: FontWeight.normal),
                    ),
                    onPressed: () {
                      Navigator.of(context).pop();
                    },
                  ),
                  CupertinoDialogAction(
                    isDestructiveAction: true,
                    child: const Text('去设置'),
                    onPressed: () {
                      launchUrlString(
                          'App-Prefs:Privacy&path=SPEECH_RECOGNITION');
                    },
                  ),
                ],
                insetAnimationDuration: const Duration(seconds: 2),
              );
            });
        return;
      }
    }

    // 判断剩余次数
    if ((AppUtil().touristLoginModel?.isVip ?? 0) == 0 &&
        (AppUtil().touristLoginModel?.freeCount ?? 0) == 0) {
      if (widget.onAlertVipTappedEvent != null) {
        widget.onAlertVipTappedEvent!();
      }
      return;
    }

    // 语音识别
    setupSpeechRecognition();

    showAnimationDialog(
      context: context,
      transitionType: TransitionType.scale,
      barrierDismissible: false,
      builder: (context) => StatefulBuilder(builder: (context, state) {
        dialogState = state;
        dialogContext = context;
        return Dialog(
          elevation: 0,
          backgroundColor: Colors.transparent,
          child: Container(
            decoration: BoxDecoration(
                borderRadius: BorderRadius.circular(13),
                color: stringToColor('FF333544')),
            constraints: BoxConstraints(
              maxHeight: ScreenUtil().screenHeight - 60,
            ),
            child: Column(
              mainAxisSize: MainAxisSize.min,
              children: [
                Stack(
                  children: [
                    Center(
                      child: Padding(
                        padding: const EdgeInsets.only(top: 20, bottom: 24),
                        child: MyTextWeight(
                            '语音输入', 18, Colors.white, FontWeight.normal),
                      ),
                    ),
                    Positioned(
                      right: 0,
                      top: 0,
                      child: IconButton(
                          padding: const EdgeInsets.all(16),
                          onPressed: () {
                            cancel();
                            stop();
                            context.pop();
                            dialogContext = null;
                            dialogState = null;
                          },
                          icon: const Icon(Icons.close)),
                    )
                  ],
                ),
                Padding(
                  padding: const EdgeInsets.only(left: 16, right: 16),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      CountDownProgressBar(
                        duration: 9,
                        width: 24,
                        height: 24,
                        strokeWidth: 4,
                        fontSize: 15,
                        initialDuration: 0,
                        controller: controller,
                        onComplete: (controller) {
                          // 规定8秒停止监听
                          cancel();
                          stop();

                          if (dialogContext != null) {
                            dialogContext!.pop();
                            dialogContext = null;
                            dialogState = null;
                          }
                          if (isNotBlank(listenContent)) {
                            widget.onSubmit(listenContent);
                            listenContent = '';
                          }
                        },
                      ),
                      const SizedBox(width: 10),
                      AnimatedTextKit(
                        totalRepeatCount: 1,
                        animatedTexts: [
                          TypewriterAnimatedText('正在收听...',
                              speed: const Duration(milliseconds: 50),
                              textStyle: const TextStyle(
                                color: Colors.white,
                                fontSize: 17,
                              )),
                        ],
                      ),
                    ],
                  ),
                ),
                // 内容
                Padding(
                  padding: EdgeInsets.only(
                      left: 34,
                      right: 34,
                      top: listenContent.length > 25 ? 20 : 40,
                      bottom: listenContent.length > 25 ? 20 : 40),
                  // child: AnimatedTextKit(
                  //   totalRepeatCount: 1,
                  //   animatedTexts: [
                  //     TypewriterAnimatedText(
                  //         listenContent,
                  //         speed: const Duration(milliseconds: 50),
                  //         textStyle: const TextStyle(
                  //           color: Colors.white,
                  //           fontSize: 17,
                  //         )),
                  //   ],
                  //   onFinished: () {
                  //
                  //   },
                  // ),
                  child: MyTextWeight(listenContent, 16,
                      stringToColor('FF18DDEB'), FontWeight.normal),
                ),

                // gif
                Container(
                  margin: const EdgeInsets.only(left: 10, right: 10, bottom: 5),
                  height: 120,
                  width: double.infinity,
                  child: Stack(alignment: Alignment.center, children: [
                    Positioned(
                      top: 0,
                      bottom: 0,
                      left: 0,
                      right: 0,
                      child: ClipRect(
                        child: OverflowBox(
                          child: Image.asset(
                            fit: BoxFit.fitWidth,
                            'assets/record_input.gif',
                          ),
                        ),
                      ),
                    ),
                  ]),
                )
              ],
            ),
          ),
        );
      }),
    );
  }

  /// 处理输入框提交
  void _handleSubmited(String text, {bool notSend = false}) {
    if (notSend) {
      var cursorPos = _textController.selection.base.offset;
      if (cursorPos < 0) {
        _textController.text = text;
      } else {
        String suffixText = _textController.text.substring(cursorPos);
        String prefixText = _textController.text.substring(0, cursorPos);
        _textController.text = prefixText + text + suffixText;
        _textController.selection = TextSelection(
          baseOffset: cursorPos + text.length,
          extentOffset: cursorPos + text.length,
        );
      }

      _focusNode.requestFocus();
      return;
    }

    if (text != '') {
      widget.onSubmit(text);
      _textController.clear();
    }
  }

  //TODO: - record recognition
  void startRecognition() => _speech.activate('zh_CN').then((_) {
        return _speech.listen().then((result) {
          print('_MyAppState.start => result $result');
          setState(() {
            _isListening = result;
          });
        });
      });

  void cancel() => _speech.cancel().then((_) {
        print('_MyAppState.onRecognitionCancel... ');
        setState(() => _isListening = false);
      });

  void stop() => _speech.stop().then((_) {
        print('_MyAppState.onRecognitionStop... ');
        setState(() => _isListening = false);
      });

  void onSpeechAvailability(bool result) =>
      setState(() => _speechRecognitionAvailable = result);

  void onRecognitionStarted() {
    print('_MyAppState.onRecognitionStarted...');
    _isListening = true;
  }

  void onRecognitionResult(String text) {
    print('_MyAppState.onRecognitionResult... $text');
    if (dialogState != null) {
      print('_MyAppState.dialogState...');
      dialogState!(() => listenContent = text);
    }
  }

  void onRecognitionComplete(String text) {
    print('_MyAppState.onRecognitionComplete... $text');

    if (isNotBlank(listenContent)) {
      if (dialogContext != null) {
        dialogContext!.pop();
      }
      widget.onSubmit(listenContent);
      listenContent = '';
      dialogContext = null;
      dialogState = null;
    }
    _isListening = false;
  }

  void errorHandler() => setupSpeechRecognition();
}
